module.exports = app => {
    const express = require('express');
    const router = express.Router({
        mergeParams: true
    });

    const Welcome = require('../../models/Welcome');
    const About = require('../../models/About');
    const Demo = require('../../models/Demo');
    const Article = require('../../models/Article');
    const Visitor = require('../../models/Visitor');
    const Action = require('../../models/Action');
    const Comment = require('../../models/Comment');
    const Resume = require('../../models/Resume');
    const deepClone = require('../../libs/tools');
    const uploadUrl = require('../../libs/uploadUrl');
    const countVisitors = require('../../libs/countVisitors');
    //获取首页信息
    router.get('/index', async (req, res) => {
        const welcome = await Welcome.find();
        const visitorsNum = await Visitor.countDocuments();
        const visitor_id = req.headers.visitor_id;
        const now = new Date();
        if (visitor_id) {
            await Visitor.findByIdAndUpdate(visitor_id, {
                lastActive: now
            })
            const visitorInfo = await Visitor.findById(visitor_id)
            res.send({
                slideData: welcome[0],
                visitorInfo
            })
        } else {
            newVisitor = {
                avatarUrl: uploadUrl + '/uploads/defaultAvatar.png',
                visitorId: visitorsNum + 1,
                lastActive: now
            }
            const newVisitorInfo = await Visitor.create(newVisitor);
            res.send({
                slideData: welcome[0],
                newVisitorInfo
            })
        }
    })
    //关于我的信息
    router.get('/about', async (req, res) => {
        const about = await About.find();
        res.send(about[0])
    })
    //获取Demo列表
    router.get('/demo', async (req, res) => {
        let page = req.query.pageNum || 1;
        let limit = req.query.pageSize || 5;
        const totalDemos = await Demo.countDocuments();
        let demoList = await Demo.find().populate('tags').skip((page - 1) * parseInt(limit)).limit(parseInt(limit));
        res.send({
            totalDemos,
            demoList
        })
    })
    //获取文章列表
    router.get('/articles', async (req, res) => {
        let page = req.query.pageNum || 1;
        let limit = req.query.pageSize || 5;
        const totalArticles = await Article.countDocuments();
        let articles = await Article.find().sort({ weight: -1, createdAt: -1 }).skip((page - 1) * parseInt(limit)).limit(parseInt(limit));
        articles.forEach(async (item) => {
            const commentNum = await Comment.countDocuments({
                object: item._id
            })

            const voteNum = await Action.countDocuments({
                object: item._id,
                type: 'Article',
                name: 'like'
            })

            await Article.findByIdAndUpdate(item._id, {
                commentNum,
                voteNum
            })
        });
        res.send({
            totalArticles,
            articles
        })
    })
    //获取文章详情
    router.get('/article/:id', async (req, res) => {
        const article = await Article.findById(req.params.id).select('+body');
        res.send(article);
    })

    //获取点赞数量
    router.get('/actions/status', async (req, res) => {
        const dto = req.query;
        //文章点赞数量
        const voteNum = await Action.countDocuments(dto);
        dto.visitor_id = req.headers.visitor_id;
        //特定访客是否点赞
        const voted = await Action.countDocuments(dto);

        res.send({
            voteNum,
            status: voted > 0
        })
    })
    //切换点赞状态
    router.post('/actions/toggle', async (req, res) => {
        const query = deepClone(req.body)
        const dto = req.body;
        dto.visitor_id = req.headers.visitor_id;
        let voted = await Action.countDocuments(dto);
        if (voted) {
            await Action.deleteMany(dto)
        } else {
            await Action.create(dto)
        }
        const updateCount = await Action.countDocuments(dto);
        const voteNum = await Action.countDocuments(query);
        res.send({
            voteNum,
            status: updateCount > 0
        })
    })
    //获取文章评论
    router.get('/comments/:id', async (req, res) => {
        const comments = await Comment.find({
            object: req.params.id
        }).populate('visitor_id')
        res.send(comments)
    })
    //提交评论
    router.post('/comments', async (req, res) => {
        const dto = req.body;
        dto.visitor_id = req.headers.visitor_id;
        const newComment = await Comment.create(dto);
        res.send(newComment)
    })
    //访客信息提交
    router.post('/visitor/edit', async (req, res) => {
        const visitorInfo = await Visitor.findByIdAndUpdate(req.headers.visitor_id, req.body);
        res.send(visitorInfo);
    })
    //访客信息查询
    router.get('/visitor', async (req, res) => {
        const id = req.headers.visitor_id
        if (id) {
            const visitorInfo = await Visitor.findById(id);
            res.send(visitorInfo);
        } else {
            const visitorsNum = await Visitor.countDocuments();
            newVisitor = {
                avatarUrl: uploadUrl + '/uploads/defaultAvatar.png',
                visitorId: visitorsNum + 1
            }
            const newVisitorInfo = await Visitor.create(newVisitor);
            res.send({
                newVisitorInfo
            })
        }
    })
    //获取底部信息栏数据
    router.get('/footer', async (req, res) => {
        const totalVisitors = await Visitor.countDocuments();
        const totalComments = await Comment.countDocuments();
        const totalArticles = await Article.countDocuments();
        const startTime = new Date(2021, 6, 30);
        const now = new Date();
        const serviceDays = parseInt((now.getTime() - startTime.getTime()) / (1000 * 60 * 60 * 24));
        //echarts图标信息
        const echartsInfo = await countVisitors(Visitor)
        const footerInfo = {
            totalVisitors,
            totalComments,
            totalArticles,
            serviceDays,
            echartsInfo
        }
        res.send(footerInfo);
    })
    //简历信息获取
    router.get('/resume', async (req, res) => {
        const fileInfo = await Resume.find();
        const title1 = fileInfo[0].title,
            title2 = fileInfo[0].title2;
        res.send({
            title1,
            title2
        })
    })
    //简历下载
    router.get('/download', async (req, res) => {
        console.log('download in')
        const fileInfo = await Resume.find();
        const fileUrl = fileInfo[0].fileUrl,
            fileName = fileInfo[0].fileName;
        res.download(fileUrl, fileName, function (err) {
            if (err) {
                console.log(err)
            } else {
                //res.send('ok')   
            }
        })
    })
    app.use('/web/api/', router)
}